package com.gitee.limaozhi.socket.lesson03.example1;

import com.gitee.limaozhi.socket.lesson02.example3.LineDelimiterDecoder;
import com.gitee.limaozhi.util.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

/**
 * @author hzlimaozhi
 * @date 2019/08/26 15:08
 */
public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8000);
        System.out.println("服务器：启动\n");

        try {
            int clientCount = 0;
            while (true) {
                clientCount++;

                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                LineDelimiterDecoder delimiterDecoder = new LineDelimiterDecoder();

                byte[] buffer = new byte[1024];
                while (true) {
                    int count = inputStream.read(buffer);
                    if (count == -1) {
                        break;
                    }

                    List<String> requests = delimiterDecoder.decode(Utils.copy(buffer, 0, count));
                    for (String request : requests) {
                        System.out.println("客户端" + clientCount + "：" + request);

                        String response = ServerLogicHandler.getResponse(request);
                        System.out.println("服务器" + clientCount + "：" + response);

                        byte[] responseBytes = LineDelimiterEncoder.encode(response);
                        outputStream.write(responseBytes);
                    }
                    System.out.println();
                }

                socket.close();
                System.out.println("客户端" + clientCount + "：关闭\n");
            }
        } finally {
            serverSocket.close();
            System.out.println("服务器：关闭");
        }
    }

}
